import { Alert, Button, Col, Form, Input, InputNumber, message, Radio, Row, Select } from 'antd';
import React, { useEffect, useState } from 'react';
import { connect } from 'react-redux';
import { USAGE_SCOPE_LIMIT } from 'src/utils/constant';
import ActionSet from '../../../components/ActionSet';
import FormItem from '../../../components/FormItem';
import ScriptEditor from '../../../components/ScriptEditor';
import useVariableData from '../../../hook/useVariableData';
import useProjectData from '../../../hook/useProjectData';
import useActionsData from '../../../hook/useActionsData';
import useDataType from '../../../hook/useDataType';
import services from '../../../services/api';
import { compare, compareClass } from '../../../utils/compare';
import { CALC_TYPE, VARIABLE_TYPE } from '../../../utils/constant';
import useAppProductEventData from 'src/hook/useAppProductEventData';
import { VARS_TYPE_LIST, VARS_TYPE } from '../../../utils/constant';
import DataTypeDesc from '../../../components/DataTypeDesc';

function VarAdd(props) {
  const { getVarList, record = {}, actionType, closeModal, freshQueryList } = props;

  const [projectCode, setProjectCode] = useState('');
  const [value, setValue] = useState({});
  const [using_variables, setUsingVariables] = useState([]);

  const [varList, setVarList] = useState([]);

  // const [dataSourceType, setDataSourceType] = useState('1');
  const [calcScript, setCalcScript] = useState();
  // 项目列表
  const projectList = useProjectData();
  // 函数列表
  const actionList = useActionsData(USAGE_SCOPE_LIMIT._FIELD);
  // 数据类型列表
  const dataTypeList = useDataType();

  // const { items, appId, eventId } = useAppProductEventData({
  //   ...props,
  //   app_id: value.app_id,
  //   event_id: value.event_id,
  //   event_name: value.event_name,
  //   product_id: value.product_id,
  //   disabled: props.actionType !== 'add' && props.actionType !== 'copy',
  //   form: props.form,
  //   layout: {
  //     className: 'tantuer-form-item3',
  //   },
  // });

  const variable = useVariableData({
    limitType: [
      VARIABLE_TYPE._FIELD,
      // VARIABLE_TYPE._FEATURE,
      // VARIABLE_TYPE._MODEL,
      // VARIABLE_TYPE._NAMELIST,
      // VARIABLE_TYPE._THIRD_FEATURE,
      // VARIABLE_TYPE._STRATEGY,
      // VARIABLE_TYPE._RISK_LEVEL,
      VARIABLE_TYPE._LITERAL,
    ],
    projectCode,
    // appId,
    // eventId,
  }); //字段添加页，默认需要字段、指标的变量

  useEffect(() => {
    // getActions(); //获取函数列表
    // if (
    //   (props.actionType === 'update' || props.actionType === 'detail') &&
    //   props.record &&
    //   props.record.field_id &&
    //   !props.isAuditLog
    // ) {
    //   getDetail(); // 获取详情
    // }
    // if (props.value && Object.keys(props.value).length > 0) {
    //   setDetail(props.value);
    // }
    if (['update', 'detail'].includes(actionType)) {
      getDetail();
    }
  }, []);
  // useEffect(() => {
  //   if (props.value && Object.keys(props.value).length > 0) {
  //     setDetail(props.value, true);
  //   }
  // }, [props.value]);

  /**获取详情 */
  function getDetail() {
    services.vars.detail({ id: record.id }).then(({ code, data, msg }) => {
      if (code === '0') {
        const { projectCode, calcType, calcScript } = data;
        setValue(data);
        handleChangeProject(projectCode);
        const param = JSON.parse(calcScript);
        if (calcType === CALC_TYPE._CONFIG) {
          param.parameters.map((item) => {
            item.var_code = item.value.var_code;
            item.var_type = item.value.var_type;
            delete item.value;
            return item;
          });
        }
        setCalcScript(calcType === CALC_TYPE._CONFIG ? param : calcScript);
      } else {
        message.error(msg);
      }
    });
  }

  // function setDetail(data, isSetFormValue) {
  //   setUsingVariables(data.using_variables);
  //   if (isSetFormValue) {
  //     props.form.setFieldsValue({
  //       data_type: data.data_type,
  //       code: data.code,
  //       name: data.name,
  //       need_calc: data.need_calc,
  //       remark: data.remark,
  //     });
  //     setTimeout(() => {
  //       props.form.setFieldsValue({
  //         calcType: data.calcType,
  //       });
  //     }, 200);
  //   }
  //   setValue(data);
  //   setVarId(data.id);
  //   if (data.calcType === CALC_TYPE._CONFIG) {
  //     setCalcContent(data.calc_content);
  //   }
  //   if (data.calcType === CALC_TYPE._SQ) {
  //     setCalcContentText(data.calc_content);
  //   }
  // }

  const handleSubmit = (e) => {
    e.preventDefault();
    props.form.validateFields((err, values) => {
      if (!err) {
        const params = {
          ...values,
          id: record.id,
        };
        if (values.calcType === CALC_TYPE._CONFIG) {
          if (!calcScript || !Object.keys(calcScript).length) {
            return message.warning('请编辑函数');
          } else {
            calcScript.parameters.map((item) => {
              item.value = {
                var_code: item.var_code,
                var_type: item.var_type,
              };
              delete item.var_code;
              delete item.var_type;
              return item;
            });
            params.calcScript = JSON.stringify(calcScript);
          }
        }
        if (values.calcType === CALC_TYPE._SQ) {
          if (!calcScript) {
            return message.warning('请编辑JavaScript脚本');
          } else {
            params.calcScript = calcScript;
          }
        }

        services.vars[props.actionType](params).then(({ code, msg }) => {
          if (code === '0') {
            message.success(msg);
            closeModal && closeModal();
            freshQueryList && freshQueryList();
          } else {
            message.error(msg);
          }
        });
      }
    });
  };

  const handleChangeScript = (value) => {
    setCalcScript(value);
  };

  const handleChangeProject = async (projectCode) => {
    setProjectCode(projectCode);
    const data = await getVarList({ projectCode });
    setVarList(data);
  };

  // const handleTypeChange = () => {
  //   props.form.setFieldsValue({
  //     max_length: 64,
  //   });
  // };
  const getFormItems = () => {
    const { projectCode, categoryCode, type = VARS_TYPE._PROCESS, name, code, dataType, calcType, remark } = value;
    return [
      {
        label: {
          label: '项目',
          className: 'tantuer-form-item3',
        },
        name: 'projectCode',
        options: {
          initialValue: projectCode,
          rules: [{ required: true, message: '请选择项目' }],
        },
        component: (
          <Select placeholder='请选择' onChange={handleChangeProject}>
            {projectList.map((it) => {
              return (
                <Select.Option value={it.code} key={it.code}>
                  {it.name}
                </Select.Option>
              );
            })}
          </Select>
        ),
      },
      {
        label: {
          label: '变量类型',
          className: 'tantuer-form-item3',
        },
        name: 'type',
        options: {
          initialValue: type,
          rules: [{ required: true, message: '请选择' }],
        },
        component: (
          <Select
            // style={{ width: '100%', ...compare(props, 'type') }}
            placeholder='请选择'
          >
            {VARS_TYPE_LIST.map((it) => {
              return (
                <Select.Option value={it.value} key={it.value}>
                  {it.label}
                </Select.Option>
              );
            })}
          </Select>
        ),
      },
      {
        label: {
          label: '变量分类',
          className: 'tantuer-form-item3',
        },
        name: 'categoryCode',
        options: {
          initialValue: categoryCode,
          rules: [{ required: true, message: '请选择' }],
        },
        component: (
          <Select
            // style={{ width: '100%', ...compare(props, 'categoryCode') }}
            placeholder='请选择'
            disabled={props.actionType !== 'add'}
          >
            {(props.form.getFieldValue('projectCode') ? varList : []).map((it) => {
              return (
                <Select.Option value={it.code} key={it.code}>
                  {it.name}
                </Select.Option>
              );
            })}
          </Select>
        ),
      },
      {
        label: {
          label: '变量名',
          className: 'tantuer-form-item3',
        },
        name: 'name',
        options: {
          initialValue: name,
          rules: [
            { required: true, message: '请填写' },
            { max: 128, message: '最长128个字符' },
            { pattern: /^[\u4E00-\u9FA5_a-zA-Z0-9]+$/, message: '限中英文数字下划线' },
          ],
        },
        component: (
          <Input placeholder='请填写' disabled={props.actionType === 'detail'} style={compare(props, 'field_name')} />
        ),
      },
      {
        label: {
          label: '变量Code',
          className: 'tantuer-form-item3',
        },
        name: 'code',
        options: {
          initialValue: code,
          rules: [
            { required: true, message: '请填写' },
            { max: 128, message: '最长128个字符' },
            { pattern: /^[_a-zA-Z0-9]+$/, message: '限英文数字下划线' },
          ],
        },
        component: (
          <Input
            disabled={props.actionType !== 'add'}
            // style={compare(props, 'code')}
          />
        ),
      },
      {
        label: {
          label: '数据类型',
          className: 'tantuer-form-item3',
        },
        name: 'dataType',
        options: {
          initialValue: dataType,
          rules: [{ required: true, message: '请选择' }],
        },
        component: (
          <Select
            // style={{ width: '95%', ...compare(props, 'dataType') }}
            placeholder='请选择'
            disabled={props.actionType === 'detail'}
            // onChange={handleTypeChange}
          >
            {dataTypeList.map((it) => {
              return (
                <Select.Option value={it.code} key={it.code}>
                  {`${it.name}(${it.code})`}
                </Select.Option>
              );
            })}
          </Select>
        ),
        after: <DataTypeDesc dataType={props.form.getFieldValue('dataType')} dataTypeList={dataTypeList} />,
      },
      {
        label: {
          label: '描述',
          className: 'tantuer-form-item3',
        },
        name: 'remark',
        options: {
          initialValue: remark,
          rules: [{ max: 256, message: '最长256个字符' }],
        },
        component: (
          <Input
            placeholder='请填写简短描述,限256字内'
            // style={compare(props, 'remark')}
            disabled={props.actionType === 'detail'}
          />
        ),
      },
      {
        label: {
          label: '计算类型',
          className: 'tantuer-form-item3',
        },
        name: 'calcType',
        options: {
          initialValue: calcType || CALC_TYPE._NONE,
          rules: [{ required: true, message: '请选择' }],
          getValueFromEvent: (e) => {
            if (
              calcScript &&
              ((e.target.value === CALC_TYPE._CONFIG && typeof calcScript !== 'object') ||
                (e.target.value === CALC_TYPE._SQ && typeof calcScript !== 'string'))
            ) {
              handleChangeScript(undefined);
            }
            return e.target.value;
          },
        },
        component: (
          <Radio.Group disabled={props.actionType === 'detail'} className={compareClass(props, 'calcType')}>
            <Radio.Button value={CALC_TYPE._NONE}>无</Radio.Button>
            <Radio.Button value={CALC_TYPE._CONFIG}>函数补全</Radio.Button>
            <Radio.Button value={CALC_TYPE._SQ}>自定义脚本</Radio.Button>
          </Radio.Group>
        ),
      },
    ];
  };

  return (
    <div className='tantuer-form'>
      <Form autoComplete='off' onSubmit={() => false} className='login-form'>
        <div className='tantuer-field-area'>
          <Row type='flex'>
            {getFormItems().map((item) => {
              return (
                <Col span={24} key={item.name}>
                  <FormItem {...props} form={props.form} item={item} colNum={1} />
                </Col>
              );
            })}
          </Row>
          {props.form.getFieldValue('calcType') === CALC_TYPE._NONE && <div />}
          {props.form.getFieldValue('calcType') === CALC_TYPE._CONFIG && (
            <Row type='flex'>
              <Col span={6} style={{ width: '120px' }} />

              <Col span={18}>
                <ActionSet
                  {...props}
                  variable={variable}
                  using_variables={using_variables}
                  onChange={handleChangeScript}
                  options={actionList}
                  value={calcScript}
                  // compareData={props.compareData && props.compareData.calc_content}
                  disabled={props.actionType === 'detail'}
                  fieldId={props.record && props.record.id}
                />
              </Col>
            </Row>
          )}
          {props.form.getFieldValue('calcType') === CALC_TYPE._SQ && (
            <ScriptEditor
              onChange={handleChangeScript}
              value={calcScript}
              disabled={props.actionType === 'detail'}
              placeholder={`1.获取字段的值语法：field("字段code"); 例如获取code为a的字段值 field("a")\n2.特殊类型的字段类型转换\n例如code为a的字段值是字符串, 获取a的int值：Integer.valueOf(field("a"))\n3.表达式\n简单版：field("a") == null&&field("b") != null\n复杂版：Integer.valueOf(field("a")) == 0&&Double.valueOf(field("c"))>5`}
            />
          )}
        </div>
        {props.actionType === 'detail' ? (
          ''
        ) : (
          <div className='form-btn'>
            <Button type='primary' onClick={handleSubmit} className='login-form-button' autoFocus={true}>
              确定
            </Button>
            <Button className='login-form-button' onClick={() => props.closeModal && props.closeModal(true)}>
              取消
            </Button>
          </div>
        )}
      </Form>
    </div>
  );
}

export default Form.create()(VarAdd);
